package com.emato.cus.task;

import com.emato.cus.config.TaskConfig;
import com.emato.cus.runnable.MyRunnable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @author hhq
 * @version 1.0.0
 * 2020/7/3
 */
@Component
@Order(value = 1)
public class ScanTask implements ApplicationRunner {

    @Autowired
    private TaskConfig taskConfig;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    MyRunnable myRunnable;

    private ScheduledFuture<?> future;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    public void startCron() {
        future = threadPoolTaskScheduler.schedule(myRunnable, new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(taskConfig.getCorn()).nextExecutionTime(triggerContext);
            }
        });
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        startCron();
    }



}

